package com.abe.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class FileDownLoadUtil {
	private FileDownloadListener listener;

	public FileDownLoadUtil() {

	}

	public void down(String url, String savePath) {
		ThreadPoolUtils.execute(new downloadThread(url, savePath));
	}

	public void setFileDownloadListener(FileDownloadListener listener) {
		this.listener = listener;
	}

	class downloadThread implements Runnable {

		private String url;
		private String savePath;

		public downloadThread(String url, String savePath) {
			this.url = url;
			this.savePath = savePath;
		}

		@Override
		public void run() {
			if (url.equals("")) {
				listener.onRequestFail("下载路径为空");
				return;
			} else if (url.length() < 4) {
				listener.onRequestFail("下载路径错误");
				return;
			} else if (url.length() > 4 && !url.substring(0, 4).equals("http")) {
				listener.onRequestFail("下载路径错误");
				return;
			}
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);
			HttpResponse response;
			try {
				response = client.execute(get);
				HttpEntity entity = response.getEntity();
				/** 数据长度 */
				long length = entity.getContentLength();
				InputStream is = entity.getContent();
				FileOutputStream fileOutputStream = null;
				if (is == null) {
					throw new RuntimeException("isStream is null");
				}
				File file = new File(savePath);
				fileOutputStream = new FileOutputStream(file);
				byte[] buf = new byte[1024];
				int ch = -1;
				int len = 0;
				do {
					ch = is.read(buf);
					len += ch;
					// 计算进度条位置
					int progress = (int) (((float) len / length) * 100);
					listener.onRefreshProgress(progress,len,length);
					if (ch <= 0)
						break;
					fileOutputStream.write(buf, 0, ch);
				} while (true);
				is.close();
				fileOutputStream.close();
				listener.onDownLoadSuccess();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				listener.onRequestFail("下载失败");
			} catch (IOException e) {
				e.printStackTrace();
				listener.onRequestFail("下载失败");
			}
			listener.onRequestFinish();
		}

	}

}
